const requests = "../../../../utils/request.js"
const app = getApp()
import {AppointOrderInterface} from "../../../../utils/request.js"
import {formatTime} from "../../../../utils/util.js"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //地址
    address:{},
    hasAddress: false,
    addressIcon:'/imgs/myaddress.png',

    //预约时间
    scheduledDate:"选择预约上门时间",
    scheduledDateChoosed:false,

    show: false,

    //留言
    note:"",
    //寄件人姓名
    senderName:"",
    //寄件人电话
    // senderPhone:"",
    //预估重量
    weight:"",
    urgent:false,
    //预计获得积分
    integration:0,
    //预约时间所需数据
  calendar:[],
  width:0,
  currentDayIndex:0,
  currentDay:"今天",
  currentTimeindex: 0,
  currentTime:"9:00-10:00",
  timeArr: [
      { "time": "9:00-10:00", "status": "空闲" }, 
      { "time": "10:00-11:00", "status": "空闲" }, 
      { "time": "11:00-12:00", "status": "空闲" }, 
      { "time": "14:00-15:00", "status": "空闲" }, 
      { "time": "15:00-16:00", "status": "空闲" }, 
      { "time": "16:00-17:00", "status": "空闲" }, 
      { "time": "17:00-18:00", "status": "空闲" },
      { "time": "18:00-19:00", "status": "空闲" }
      ]
  },
  urgentChange({ detail }) {
    const urgentNow = this.data.urgent
    wx.showModal({
      title: '提示',
      content: urgentNow?'取消加急处理':'确认要加急处理吗',
      success: (res) => {
        if (res.confirm) {
          this.setData({ urgent: detail });
        }
      },
    });
  },
  showPopup() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  bindNoteInput(e)
  {
    const note = e.detail.value
    this.setData({
      note
    })
    // console.log(this.data.note)
  },
  bindWeightInput(e)
  {
    const weight = e.detail.value

    this.setData({
      weight,
      // integration:typeof Number(weight)=="Number"?Number(weight)*15:0
      integration:Number(weight)*15
    })
  },
  bindNameInput(e)
  {
    const senderName = e.detail.value
    this.setData({
      senderName
    })
  },
  // bindPhoneInput(e)
  // {
  //   const senderPhone = e.detail.value
  //   this.setData({
  //     senderPhone
  //   })
  // },
  submitOrder()
  {
    if(!this.data.hasAddress)
    {
      wx.showToast({
        title: '请选择地址',//提示文字
        duration:2000,//显示时长
        mask:true,//是否显示透明蒙层，防止触摸穿透，默认：false  
        icon:'error', //图标，支持"success"、"loading"  
      })
    }
    else if(!this.data.scheduledDateChoosed)
    {
      wx.showToast({
        title: '请选择时间',//提示文字
        duration:2000,//显示时长
        mask:true,//是否显示透明蒙层，防止触摸穿透，默认：false  
        icon:'error', //图标，支持"success"、"loading"  
      })
    }
    else{
      let that = this
      wx.showToast({
        title: '提交成功',//提示文字
        duration:2000,//显示时长
        mask:true,//是否显示透明蒙层，防止触摸穿透，默认：false  
        icon:'success', //图标，支持"success"、"loading"  
        success:async function(){ 

          let goodsStr = "未分类垃圾"

          let dateArr = that.data.scheduledDate.split(/-|:|\s/)
          const startTime = formatTime(new Date(dateArr[0],parseInt(dateArr[1])-1,dateArr[2],dateArr[3]))
          const endTime =  formatTime(new Date(dateArr[0],parseInt(dateArr[1])-1,dateArr[2],dateArr[5]))

          let res = await AppointOrderInterface("测试地区编号",undefined,undefined,that.data.integration,0,goodsStr,undefined,0,that.data.address.address,startTime,endTime,app.globalData.userInfo.nickName,that.data.note,that.data.address.telphone,that.data.urgent?1:0,that.data.weight,formatTime(new Date()),app.globalData.openid,'add')
          // let res = requests.addAppointOrder()
          setTimeout(function(){
            wx.navigateTo({
              url: '../success/index',
            })},2000
          )

        },//接口调用成功
        fail: function () { },  //接口调用失败的回调函数  
        complete: function () { } //接口调用结束的回调函数  
     })
    }
  },

  selectDay(e)
  {
    console.log(e)
    const currentDayIndex = e.currentTarget.dataset.index
    const currentDay = e.currentTarget.dataset.date
    this.setData({
      currentDayIndex,
      currentDay
    })

  },

  selectTime(e)
  {
    // console.log(e)
    const currentTimeindex = e.currentTarget.dataset.tindex
    const currentTime = e.currentTarget.dataset.time
    const scheduledDate = this.data.currentDay +" "+ currentTime
    this.setData({currentTime,
    scheduledDate,
    scheduledDateChoosed:true
    })
    this.onClose();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this;
    function getThisMonthDays(year, month) {
     return new Date(year, month, 0).getDate();
    }
   // 计算每月第一天是星期几
    function getFirstDayOfWeek(year, month) {
     return new Date(Date.UTC(year, month - 1, 1)).getDay();
    }
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    const cur_date=date.getDate();
    const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
    //利用构造函数创建对象
    function calendar(date,week){
     this.date=cur_year+'-'+cur_month+'-'+date;
     if(date==cur_date){
      this.week = "今天";
     }else if(date==cur_date+1){
      this.week = "明天";
     }else{
      this.week = '星期' + week;
     }
    }
    //当前月份的天数
    var monthLength= getThisMonthDays(cur_year, cur_month)
    //当前月份的第一天是星期几
    var week = getFirstDayOfWeek(cur_year, cur_month)
    var x = week;
    for(var i=1;i<=monthLength;i++){
     //当循环完一周后，初始化再次循环
     if(x>6){
      x=0;
     }
     //利用构造函数创建对象
     that.data.calendar[i] = new calendar(i, [weeks_ch[x]][0])
     x++;
    }
    //限制要渲染的日历数据天数为7天以内（用户体验）
    var flag = that.data.calendar.splice(cur_date, that.data.calendar.length - cur_date <= 7 ? that.data.calendar.length:7)
    that.setData({
     calendar: flag,
     currentDay:flag[0].date
    })
    //设置scroll-view的子容器的宽度
    that.setData({
     width: 186 * parseInt(that.data.calendar.length - cur_date <= 7 ? that.data.calendar.length : 7)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getAddressinStorage();

  },
/**
   * 获取内存中的地址缓存
   */
  getAddressinStorage()
  {
    const self = this;
    wx.getStorage({
      key:'address',
      success(res) {
        // console.log("获取地址")
        // console.log(res.data)
        self.setData({
          address: res.data,
          hasAddress: true
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})